import React from "react"
import {
  Form,
  Modal,
  Row,
  Col,
  Button,
  Checkbox,
  DatePicker,
  Spin,
} from "antd";

import moment from "moment";
import DelayInput from "../flowdetailpannel/DelayInput";
import FlowHandleBaseForm from "./FlowHandleBaseForm"
import yanqi from "../../assets/images/yanqi.png";

import styles from "./TransferForm.less";

const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 },
};

const datetimeConfig = [
  { label: "天", key: "day" },
  { label: "时", key: "hour", max: 23 },
  { label: "分", key: "minute", max: 59 },
];

@Form.create()
class DelayForm extends FlowHandleBaseForm {
  constructor(props) {
    super(props);

    this.state = {
      timeoutSetting: {
        day: 0,
        hour: 0,
        minute: 0,
      },
      disabled: false,
      noticeUserSelectorVisible: false,
      noticeUsers: [], // 自定添加的通知接收人
    };
  }

  componentDidMount() {
    /*
    const { dispatch, form } = this.props;
    dispatch({
      type: "FlowChart/getTemplateListByType",
      payload: {
        type: "TASK_DEPLAY",
      },
    }).then(({ errCode, datas }) => {
      if (errCode === 0 && datas.length > 0) {
        // console.log(datas[0]);
        form.setFieldsValue({
          title: datas[0].title,
          content: datas[0].content,
        });
        this.setState({ disabled: true });
      } else {
        this.setState({ disabled: false });
      }
    });
    */
    this.noticeKey = '延期';
    this.loadMessageTheme();
  }

  handleOk = () => {
    const {
      form,
      onCancel,
      dispatch,
      taskId,
      applyUserId,
      getList,
      timeout,
    } = this.props;
    const { timeoutSetting, noticeUsers } = this.state;
    const userCode = sessionStorage.getItem("USER_CODE"); // 当前登陆人

    if (moment(timeout.task_timeout).isBefore(moment())) {
      this.openNotificationWithIcon(
        "error",
        "",
        `当前时间已超过节点超时时间，不可发起延期`,
      );
      return;
    }

    if (timeout.process_timeout) {
      const deleyTime = moment(timeout.task_timeout)
        .add(timeoutSetting.day, "days")
        .add(timeoutSetting.hour, "hours")
        .add(timeoutSetting.minute, "minutes");

      // console.log(moment(deleyTime).format("YYYY-MM-DD HH:mm:ss"));
      if (moment(timeout.process_timeout).isBefore(deleyTime)) {
        this.openNotificationWithIcon(
          "error",
          "",
          `当前流程超时时间为${timeout.process_timeout},节点延期不得超过该时间`,
        );
        return;
      }
    }

    form.validateFields((err, values) => {
      if (err) {
        // 通知消息主题没有配置可以提交
        if (Object.keys(err).length > 1 || !err.messageThemName) {
          return;
        }
      }

      const { user, title, content } = values;
      const receiveMessagers = [];
      if (user.includes("publisher")) {
        receiveMessagers.push(applyUserId);
      }

      receiveMessagers.push(...noticeUsers.map(({ userCode: _code }) => _code));

      dispatch({
        type: "FlowHandle/delayTask",
        payload: {
          taskId,
          title,
          content,
          ...timeoutSetting,
          userCode,
          receiveMessagers,
        },
      }).then(({ errCode, errMsg }) => {
        if (errCode === 0) {
          onCancel("delayVisible", false);
          this.openNotificationWithIcon("success", "", "延期成功");
          if (getList instanceof Function) {
            getList();
          }
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      });
    });
  };

  onTimeoutValueChange = (valueObj) => {
    const { timeoutSetting } = this.state;
    this.setState({ timeoutSetting: { ...timeoutSetting, ...valueObj } });
  };

  render() {
    const { timeoutSetting, disabled } = this.state;
    const { form, onCancel, visible, confirmLoading, timeout } = this.props;

    const options = [{ label: "发起人", value: "publisher" }];

    const { getFieldDecorator } = form;

    const customUsers = this.getCustomNoticeUsers()

    return (
      <Modal
        title="延期"
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => onCancel("delayVisible", false)}
        width="650px"
        centered
        destroyOnClose
        className={styles.root}
        hideRequiredMark
        labelAlign="left"
        confirmLoading={confirmLoading}
        footer={[
          <Button key="back" onClick={() => onCancel("delayVisible", false)}>
            取消
          </Button>,
          <Button
            key="ok"
            type="primary"
            onClick={this.handleOk}
            loading={confirmLoading}
          >
            确认延期
          </Button>,
        ]}
      >
        <Spin spinning={confirmLoading}>
          <Form {...formItemLayout}>
            <Row>
              <Col span={12}>
                <img src={yanqi} alt="" className={styles.marginBo} />

                <div>
                  <div className={styles.formLabelRed}>超时时间：</div>
                  <Form.Item label="">
                    {getFieldDecorator("time", {
                      initialValue: moment(timeout.task_timeout),
                      rules: [{ required: true, message: "请输入消息标题" }],
                    })(
                      <DatePicker
                        showTime
                        placeholder="Select Time"
                        disabled
                        format="YYYY-MM-DD HH:mm:ss"
                        suffixIcon={null}
                      />,
                    )}
                  </Form.Item>
                </div>
                <div>
                  <div className={styles.formLabelRed}>选择延期时间：</div>
                  <div className={styles.delay_box}>
                    {datetimeConfig.map(({ label, key, ...rest }) => (
                      <DelayInput
                        key={key}
                        label={label}
                        name={key}
                        value={timeoutSetting[key]}
                        onBlur={this.onTimeoutValueChange}
                        {...rest}
                      />
                    ))}
                  </div>
                </div>
              </Col>
              <Col span={12}>
                {/*
                <div>
                  <div className={styles.formLabel}>消息标题：</div>
                  <Form.Item label="">
                    {getFieldDecorator("title", {
                      rules: [
                        { max: 100, message: "请不要超过100个字符" },
                        { required: true, message: "请输入消息标题" },
                      ],
                    })(<Input placeholder="请输入" disabled={disabled} />)}
                  </Form.Item>
                </div>
                <div>
                  <div className={styles.formLabel}>消息内容：</div>
                  <Form.Item label="">
                    {getFieldDecorator("content", {
                      rules: [
                        { max: 100, message: "请不要超过100个字符" },
                        { required: true, message: "请输入消息内容" },
                      ],
                    })(
                      <TextArea
                        placeholder="请输入消息内容"
                        rows={7}
                        style={{ height: "175px" }}
                        disabled={disabled}
                      />,
                    )}
                  </Form.Item>
                </div>
                */}
                { this.renderNoticeTheme() }
                <div className={styles.last}>
                  <span>消息接收人：</span>
                  <Form.Item label="" {...formItemLayout}>
                    {this.renderNoticeUsers(
                      null, 
                      customUsers, 
                      getFieldDecorator("user", {
                        initialValue: ["publisher"] || null,
                        rules: [],
                      })(
                        <Checkbox.Group
                          options={options}
                          // defaultValue={["publisher"]}
                        />,
                      ),
                      disabled
                    )}
                  </Form.Item>
                </div>
              </Col>
            </Row>
          </Form>
        </Spin>
      </Modal>
    );
  }
}

export default DelayForm;
